const mysql = require('mysql');
// 第一个连接对象
let conn = mysql.createConnection({
	port: '3306',
	user: 'root',
	password: 'root',
	database: 'journalism',
	host: '127.0.0.1',
	connectTimeout: 1000 * 60 * 60
});


function query(sql, callback, param) {
	conn = mysql.createConnection(conn.config);
	// 连接数据库
	conn.connect();
	//执行过程
	if (param) {
		conn.query(sql, param, (err, data) => {
			if (err) {
				console.error(err)
			} else {
				callback(data)
			}
		})
	} else {
		conn.query(sql, (err, data) => {
			if (err) {
				console.error(err)
			} else {
				callback(data)
			}
		})
	}
	conn.end()
}


// 增
function add(param, condition) {
	const sql = `INSERT INTO ${condition}`;
	return new Promise(resolve => {
		// console.log(sql, 'llllllllllllllll');
		//执行过程
		query(sql, data => {
			resolve(data)
		}, param)
	})
}
// 删
function del(table = 'users', condition) {
	const sql = `DELETE FROM ${table} where ${condition}`;
	// console.log(sql);
	//执行过程
	query(sql, data => {
		console.log(data)
	})
}

// 改
function edit(table = 'users', param, condition) {
	const sql = `UPDATE ${table} SET ${condition}`;
	//执行过程
	query(sql, data => {
		console.log(data)
	}, param)
}

// 完整的表格查询
function search(table = 'users') {
	const sql = `SELECT * FROM ${table}`;
	//执行过程
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data);
		});
	});
}
// 条件查询
function searchBy(table = 'users', condition) {
	const sql = `SELECT * FROM ${table} WHERE ${condition}`;
	console.log(sql);
	//执行过程
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data);
		});
	});
};
// 聚合函数查询
function aggregation(table = 'users', formula, condition) {
	const sql = `select $(formula)(*) from ${table} where ${condition}`;
	// console.log(sql, `---------rerwer-------------`)
	query(sql, data => {
		console.log(data)
	}, formula)
}


module.exports = {
	add,
	del,
	edit,
	search,
	searchBy,
	aggregation
}
